package org.aeon.newsmanagersystem.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.aeon.newsmanagersystem.pojo.NewsUsers;
import org.aeon.newsmanagersystem.service.NewsUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


/**
 * @author: MissingAeon
 * @date: 2024/3/27 17:28
 * @description:
 */
@Slf4j
@Controller
@RequestMapping("/users")
public class NewsUsersController {
    private final NewsUsersService newsUsersService;

    @Autowired
    public NewsUsersController(NewsUsersService newsUsersService) {
        this.newsUsersService = newsUsersService;
    }

    @PostMapping("/doLogin")
    public String login(HttpSession session,
                        RedirectAttributes attr,
                        @RequestHeader("Referer") String referer,
                        NewsUsers user,
                        HttpServletResponse resp,
                        HttpServletRequest req) {
        final NewsUsers logined = newsUsersService.login(user);
        log.debug("当前登录：{}", logined);
        session.setAttribute("user", logined);
        session.setMaxInactiveInterval(60 * 5);
        // log.debug("来自{}网站", referer);
        if (logined != null) {
            // 保存到 Cookie
            final Cookie username = new Cookie("username", user.getUname());
            final Cookie password = new Cookie("password", user.getUpwd());
            final int maxAge = 60 * 60 * 24 * 7;
            username.setMaxAge(maxAge);
            password.setMaxAge(maxAge);
            final String path = req.getContextPath() + "/news";
            username.setPath(path);
            password.setPath(path);
            resp.addCookie(username);
            resp.addCookie(password);

            switch (logined.getUrole()) {
                case 1 -> {
                    return "redirect:" + referer;
                }
                case 2 -> {
                    return "redirect:/users/admin";
                }
                default -> {
                    session.invalidate();
                    attr.addFlashAttribute("loginError", "身份状态错误！");
                    return "redirect:/news";
                }
            }
        }
        attr.addFlashAttribute("loginError", "账号密码错误！");
        return "redirect:/news";
    }

    @GetMapping("/logout")
    public String login(HttpSession session) {
        session.invalidate();
        return "redirect:/news";
    }
}
